﻿<?php
/**
 * Created by kdpay.
 * User: Bean William
 * Date: 2016/11/10
 * Desc: 口袋支付实类
 */
header( "content-type:text/html; charset=gbk" );
class KDPay{
    //商户ID与商户秘钥
    private $P_UserId;
    private $SafeStr;

    //充值类型id 具体数值查看对接文档
    private $P_ChannelId;
    //充值金额与充值价格
    private $P_FaceValue;
    private $P_Price;
    private $P_Quantity=1;
    //银行充值类型
    private $P_Description ="";
    //卡类充值时的卡号卡密参数
    private $P_CardId = "";
    private $P_CardPass ="";
    //支付订单
    private $P_OrderId;
    //网银支付网关
    private $bankGateWay = "https://api.dq.cn/pay/KDBank.aspx";
    //点卡支付网关
    private $cardGateWay = "https://gateway.duqee.com/pay/KDCard.aspx";
    //获取最新网关地址url
    public $getGateWayUrl = "https://GetUrl.DuQee.Com/pay/KDSubmitUrl.aspx";
    //取码网关
    public $fetchQRStrGateway = 'https://GateWay.DuQee.com/pay/KDQRSrc.aspx';
    //存储最新网关txt文件,默认为gatewayUrl.txt
    public $restoreGateWayTXT = './gatewayUrl.txt';
    //订单查询接口
    public $queryGateway = "http://api.duqee.com/pay/query.aspx";
    //异步回调地址
    public $P_Result_URL = "";
    //同步回调地址
    public $P_Notify_URL = "";

    /**
     * KDPay constructor.
     * @param string $UserId 商户ID
     * @param string $SafeW 商户密钥
     */
    public function __construct($UserId,$SafeW)
    {
        if(empty($UserId) || empty($SafeW))
        {
            exit('<script>alert("口袋类初始化出错！(商户ID或秘钥不能为空！)");window.history.go(-1);</script>');
        }
        $this->P_UserId = $UserId;
        $this->SafeStr = $SafeW;

    }

    /**
     * 设置银行类型
     * @param int $payDescription 银行类型
     */
    public function setPayChannel($payDescription=1)
    {
        if($payDescription < 10000)
        {
            $this->P_ChannelId = $payDescription;
        }
        else {
            $this->P_ChannelId = 1;
            $this->P_Description = $payDescription;
        }

    }

    /**
     * 获取通道值
     * @return integer mixed 通道值
     */
    public function getPayChannel()
    {
        return $this->P_ChannelId;
    }

    /**
     * 设置支付金额
     * @param float $payMoney 支付金额
     */
    public function setFaveValue($payMoney)
    {
        if(!is_numeric($payMoney))
        {
            die('<script>alert("提交金额出错！'.$payMoney.'");window.history.go(-1);</script>');
        }
        $this->P_FaceValue = $payMoney;
        $this->P_Price = $payMoney;
    }

    /**
     * 生成订单
     */
    public function generateOrder()
    {
        $orderSn = "KDP".date('YmdHis'.rand(0,999),time());
        $this->P_OrderId = $orderSn;
    }

    /**
     * 获取订单号
     * @return string 订单号
     */
    public function getOrder()
    {
        return $this->P_OrderId;
    }

    /**
     * 设置卡号卡密
     * @param string $card_id 卡号
     * @param string $card_pass 卡密
     */
    public function setCard($card_id="",$card_pass="")
    {
        $this->P_CardId = $card_id;
        $this->P_CardPass = $card_pass;
    }

    /**
     * 获取签名字符串
     * @return string 签名串
     */
    public function getPostKey()
    {
        $str = $this->P_UserId.'|'.$this->P_OrderId.'|'.$this->P_CardId.'|'.$this->P_CardPass
            .'|'.$this->P_FaceValue.'|'.$this->P_ChannelId.'|'.$this->SafeStr;

        $post_key = md5($str);
        return $post_key;
    }





    /**
     * 设置同步和异步地址
     * @param string $notify_url 同步跳转地址
     * @param string $result_url 异步通知地址
     */
    public function setNotifyAndResult($notify_url,$result_url="http://www.baidu.com")
    {
        $this->P_Notify_URL = $notify_url;
        $this->P_Result_URL = $result_url;
    }

    /**
     * 获得最新支付网关
     * @param string $type 支付类型 bank为网银支付，card为卡类支付
     * @return mixed|string 支付网关
     */
    public function getGateWay( $type = 'bank' ){
        $P_TimesTamp = time();
        //判断类型 bank为网银支付方式，card为点卡支付方式
        $P_ServiceName = ($type == 'bank') ? 'GetBankGateway' : 'GetCardGateway';
        $signStr = $this->P_UserId . '|' . $P_ServiceName . '|' .$P_TimesTamp . '|' . $this->SafeStr;

        $sign = md5($signStr);

        //组装获取最新网关url
        $url  = $this->getGateWayUrl . '?P_UserId=' . $this->P_UserId . '&';
        $url .=  'P_ServiceName=' . $P_ServiceName . '&';
        $url .=  'P_TimesTamp=' . $P_TimesTamp . '&';
        $url .=  'P_PostKey=' . $sign ;
        $content = $this->curlGet($url);

        $deal_msg = json_decode($content , true);


        $gatewayArr = $this->getGatewayFromTXT();
        if( $deal_msg['P_Errcode'] != '0')
        {
            if( $gatewayArr[$type] == null)
                return $type == 'bank' ? $this->bankGateWay : $this->cardGateWay;
            else
                return$gatewayArr[$type];
        }
        //获取提交url
        $submitUrl = $deal_msg['P_SubmitUrl'];
        $gatewayArr[$type] = $submitUrl;
        $this->updateGatewayToTXT($gatewayArr);
        return $submitUrl;

    }

    /**
     * 初始化保存txt
     */
    public function initialGatewayTXT( $fileName ){
        if( !file_exists( $fileName ) )
        {
            $fp = fopen($fileName, 'w');
            $array = array('bank' => '',
                'card' => '');
            $gatewayJson = json_encode($array);
            fwrite($fp,$gatewayJson);
            fclose($fp);
        }

        $this->restoreGateWayTXT = $fileName;
    }

    /**
     * 从txt内获取网关
     * @return array 网关数组
     */
    public function getGatewayFromTXT(){
        $content = file_get_contents($this->restoreGateWayTXT);
        return json_decode($content,true);
    }

    /**
     * @param array 网关数组
     */
    public function updateGatewayToTXT( $gateway=array() ){
        $gatewayJSon = json_encode($gateway);
        file_put_contents($this->restoreGateWayTXT,$gatewayJSon);
    }

    /**
     * curl get方法
     * @param String 抓取url
     * @return string 抓取的内容
     */
    public function curlGet( $url )
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $content = curl_exec($ch);
        curl_close($ch);
        return $content;

    }

    /**
     * 获取取码url的内容
     * @return bool|string 内容字符串
     */
    public function getFetchQRStrContent()
    {
        $channelId = $this->P_ChannelId;
        //目前只支持微信扫码21通道和wap微信33通道
        if( $channelId != 21 && $channelId != 33 && $channelId !=2 && $channelId!=36)
        {
            echo '取码接口不支持此通道' .$channelId;
            return true;
        }
        //生成订单号
        $this->generateOrder();
        $url = $this->fetchQRStrGateway."?P_UserId=".$this->P_UserId;
        $url.= "&P_OrderId=".$this->P_OrderId;
        $url.= "&P_CardId=".$this->P_CardId;
        $url.= "&P_CardPass=".$this->P_CardPass;
        $url.= "&P_FaceValue=".$this->P_FaceValue;
        $url.= "&P_ChannelId=".$channelId;
        $url.= "&P_Description=".$this->P_Description;
        $url.= "&P_Price=".$this->P_Price;
        $url.= "&P_Quantity=".$this->P_Quantity;
        $url.= "&P_PostKey=".$this->getPostKey();
        $url.= "&P_Result_URL=".$this->P_Result_URL;
        $url.= "&P_Notify_URL=".$this->P_Notify_URL;
        $url.= "&P_Subject=我的项目";

        $content = $this->curlGet($url);
        return $content;

    }

    /**
     * 获取跳转支付url
     * @param string $pay_type 提交类型 bank为网银支付, type=card为点卡支付
     * @return string 支付跳转url
     */
    public function getRedirectUrl($pay_type ='bank')
    {
        //生成订单号
        $this->generateOrder();

        $domain_url = $this->getGateWay($pay_type);
        $url = $domain_url."?P_UserId=".$this->P_UserId;
        $url.= "&P_OrderId=".$this->P_OrderId;
        $url.= "&P_CardId=".$this->P_CardId;
        $url.= "&P_CardPass=".$this->P_CardPass;
        $url.= "&P_FaceValue=".$this->P_FaceValue;
        $url.= "&P_ChannelId=".$this->P_ChannelId;
        $url.= "&P_Description=".$this->P_Description;
        $url.= "&P_Price=".$this->P_Price;
        $url.= "&P_Quantity=".$this->P_Quantity;
        $url.= "&P_PostKey=".$this->getPostKey();
        $url.= "&P_Result_URL=".$this->P_Result_URL;
        $url.= "&P_Notify_URL=".$this->P_Notify_URL;
        $url.= "&P_Subject=我的项目";
        return $url;
    }


    /**
     * 获取订单查询url
     * @param string $order_id  订单号
     * @param integer $channel_id 充值类型
     * @param float $faceValue 支付金额
     * @param string $card_id 卡号
     * @return string 查询url
     */
    public function queryOrderUrl($order_id,$channel_id,$faceValue,$card_id="")
    {
        //获取查询的postKey
        $queryStr  = 'P_UserId='.$this->P_UserId;
        $queryStr .= '&P_OrderId='.$order_id;
        $queryStr .= '&P_ChannelId='.$channel_id;
        $queryStr .= '&P_CardId='.$card_id;
        $queryStr .= '&P_FaceValue='.$faceValue;
        $md5Str = $queryStr.'&P_PostKey='.$this->SafeStr;

        $postKey = md5($md5Str);
        $P_PostKey = iconv('UTF-8','gb2312//IGNORE',$postKey);

        $url = $this->queryGateway.'?'.$queryStr.'&P_PostKey='.$P_PostKey;

        return $url;
    }



}

?>